# coding=utf-8
from django.shortcuts import redirect, render, get_object_or_404
from django.contrib.auth import authenticate, login, logout
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
import requests
from app.models import User, Star
from conf import *
from utils import *
from django.contrib import messages


def index(request):
    user_id = request.GET.get('user', None)
    if user_id is not None:
        try:
            user = User.objects.get(pk=user_id)
        except:
            user = None
    else:
        user = None
    config = get_jsapi_signature("%s%s" % (SITE_DOMAIN, request.get_full_path()))
    if config is None:
        return 'server busy, try again'
    #return render(request, 'index.html', {'appId': APP_ID})
    data = get_data()
    data['people'] = int(data['people']) + User.objects.count()
    return render(request, 'index.html', {'config': config, 'data': data, 'user': user})


def auth(request):
    try:
        code = request.GET['code']
    except KeyError:
        print('denied')
        return "You denied the request"
    r = requests.get(
        "https://api.weixin.qq.com/sns/oauth2/access_token?" +
        "appid=%s&secret=%s&code=%s&grant_type=authorization_code"
        %(APP_ID, APP_SECRET, code))
    res = r.json()
    try:
        openid = res['openid']
    except KeyError:
        print(res['errmsg'])
        return None
    user = User.objects.get(wechat_openid=openid)
    if user is None:
        redirect('/user/upload?openid=%s' % openid)
    redirect('/user/%d' % user.id)


def dashboard(request):
    if request.method == 'GET':
        if request.user.is_authenticated():
            fake_data = get_data()
            return render(request, 'dashboard.html', {'data': fake_data})
        else:
            return render(request, 'login.html')
    elif request.method == 'POST':
        data = request.POST
        user = authenticate(username=data['username'], password=data['passwd'])
        if user is not None:
            if user.is_active:
                login(request, user)
                fake_data = get_data()
                return render(request, 'dashboard.html', {'message': '登录成功', 'data': fake_data})
            else:
                return render(request, 'login.html', {'message': '帐号未激活'})
        else:
            return render(request, 'login.html', {'message': '用户名或密码错误'})

def star_upload(request):
    if request.method != 'POST':
        return '非法请求'
    if not request.user.is_authenticated():
        return '请登录'
    data = request.POST
    try:
        file = request.FILES['picture']
        file_type = file.content_type.split('/')[1]
        start_picture = save_image(file_type, 'upload/star', file.read())
    except:
        messages.add_message(request, messages.INFO, "请上传图片")
        return redirect(dashboard)
    name = data.get('name', None)
    star = Star.objects.create(picture_path=start_picture, name=name)
    messages.add_message(request, messages.INFO, "上传成功")
    return redirect(dashboard)


def set_data(request):
    if request.method != 'POST':
        return '非法请求'
    if not request.user.is_authenticated():
        return '请登录'
    data = request.POST
    try:
        data = {
            'money': int(data['money']),
            'people': int(data['people']),
            'year': int(data['year']),
            'month': int(data['month']),
            'day': int(data['day']),
        }
    except:
        messages.add_message(request, messages.INFO, "请填写完整信息")
        return redirect(dashboard)
    save_data(data)
    messages.add_message(request, messages.INFO, "更改成功")
    return redirect(dashboard)

def user_logout(request):
    logout(request)
    return redirect(dashboard)

def user_list(request):
    users = User.objects.all()
    paginator = Paginator(users, 30)
    page = request.GET.get('page')
    try:
        users = paginator.page(page)
    except PageNotAnInteger:
        users = paginator.page(1)
    except EmptyPage:
        users = paginator.page(paginator.num_pages)
    return render(request, 'users.html', {'users': users})